import 'package:flutter/material.dart';
import 'package:flutter_again/dao/website_link_dao.dart';
import 'package:flutter_again/models/website_link.dart';
import 'package:flutter_again/repository/website_link_repository.dart';
import 'package:flutter_again/utils/log.dart';

import 'package:go_router/go_router.dart';

class SurfingPage extends StatefulWidget {
  const SurfingPage({ super.key });

  @override
  State<SurfingPage> createState() => _SurfingPage();
}

class _SurfingPage extends State<SurfingPage> {
  final _repository = WebsiteLinkRepository(localDataSource:  WebsiteLinkDao());
  final _formKey = GlobalKey<FormState>();
  final List<WebsiteLink> list = [];
  final formModel = <String, dynamic>{
    'id': -1,
    'title': '',
    'description': '',
    'url': '',
  };

  @override
  void initState() {
    super.initState();
    getList();
  }

  Future<void> getList() async {
    log.d('开始获取列表');
    final res = await _repository.read();
    log.d('list: $res');
    setState(() {
      list.addAll(res);
    });
  }

  void tapItem(WebsiteLink item) {
    context.pushNamed('webview', queryParameters: {'url': item.url });
  }

  void delItem(WebsiteLink item) async {
    await _repository.delete(item);
    setState(() {
      list.remove(item);
    });
  }

  void handleCancel(BuildContext context) {
    Navigator.of(context).pop();
  }

  Future<void> handleSubmit(BuildContext context) async {
    if (!_formKey.currentState!.validate()) return;
    WebsiteLink item;
    final isCreate = formModel['id'] == -1;
    if (isCreate) {
      item = await _repository.create(CreateWebsiteLinkRequest.fromJson(formModel));
    } else {
      item = await _repository.update(UpdateWebsiteLinkRequest.fromJson(formModel));
    }
    log.d('此次的item.id: ${item.id}');
    setState(() {
      if (isCreate) {
        list.add(item);
      } else {
        final i = list.indexWhere((it) => it.id == item.id);
        list.setAll(i, [item]);
      }
      if (mounted) {
        handleCancel(context);
      }
    });
  }

  void popupDialog() {
    final titleText = formModel['id'] == -1 ? '添加网址' : '编辑场次';
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(titleText),
          content: SizedBox(
            height: 240,
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    initialValue: formModel['title'],
                    decoration: const InputDecoration(
                      labelText: '标题'
                    ),
                    onChanged: (value) => formModel['title'] = value,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入网址标题';
                      }
                      return null;
                    },
                  ),
                  TextFormField(
                    initialValue: formModel['description'],
                    onChanged: (value) => formModel['description'] = value,
                    decoration: const InputDecoration(
                      labelText: '描述'
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入网址描述';
                      }
                      return null;
                    },
                  ),
                  TextFormField(
                    initialValue: formModel['url'],
                    onChanged: (value) => formModel['url'] = value,
                    decoration: const InputDecoration(
                      labelText: 'url'
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入网址链接地址';
                      }
                      return null;
                    },
                  ),
                ],
              ),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => handleCancel(context),
              child: const Text('取消'),
            ),
            TextButton(

              onPressed: () => handleSubmit(context),
              child: const Text('确认'),
            ),
          ],
        );
      }
    );
  }

  void popupAdd() {
    formModel['title'] = '';
    formModel['id'] = -1;
    formModel['description'] = '';
    formModel['url'] = '';
    popupDialog();
  }

  void popupEdit(WebsiteLink item) {
    formModel['title'] = item.title;
    formModel['id'] = item.id;
    formModel['description'] = item.description;
    formModel['url'] = item.url;
    popupDialog();
  }

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      body: SafeArea(
        child: ListView.builder(
          itemCount: list.length,
          itemBuilder: (context, i) {
            final item = list[i];
            return ListTile(
              leading: Container(
                width: 30,
                height: 30,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(6)),
                  color: Colors.blue,
                ),
                child: Center(
                  child: Text(
                    item.title.substring(0, 1),
                    style: TextStyle(fontSize: 24, color: Colors.white),
                  ),
                ),
              ),
              title: Text(item.title),
              subtitle: Text(item.description),
              shape: Border(bottom: BorderSide(color: Color.fromRGBO(0, 0, 0, 0.2))),
              style: ListTileStyle.list,
              trailing: IconButton(onPressed: () => delItem(item), icon: Icon(Icons.delete_forever)),
              onTap: () => tapItem(item),
              onLongPress: () => popupEdit(item),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: popupAdd,
        child: const Icon(Icons.add),
      ),

    );
  }
}
